package com.madi.company.ui.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aspsine.irecyclerview.animation.ScaleInAnimation;
import com.jaydenxiao.common.base.BaseActivity;
import com.madi.company.R;
import com.madi.company.bean.ProfessionTypeEntity;
import com.madi.company.contract.ProfessionTypeContract;
import com.madi.company.model.ProfessionTypeModel;
import com.madi.company.presenter.ProfessionTypePresenter;
import com.madi.company.ui.main.adapter.ProfessionTypeAdapter;
import com.madi.company.utils.SerializableMap;
import com.madi.company.widget.ClearEditText;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersTouchListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;


/*
 *   Created by 丁宁
 *   on 2016/12/9.
 *   des: 职位类别 列表页面
 */

public class ProfessionActivity extends BaseActivity<ProfessionTypePresenter, ProfessionTypeModel> implements ProfessionTypeContract.View {

    @Bind(R.id.backBtn)
    LinearLayout mBackBtn;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.textOne)
    TextView mTextOne;
    @Bind(R.id.filter_edit)
    ClearEditText mFilterEdit;
    @Bind(R.id.Btn_ProfessionType)
    Button mBtnProfessionType;
    @Bind(R.id.list)
    RecyclerView mListView;
    @Bind(R.id.activity_profession)
    LinearLayout mActivityProfession;
    @Bind(R.id.select_number)
    TextView mSelectNumber;
    @Bind(R.id.CheckBoxProfessionList)
    CheckBox mCheckBoxProfessionList;
    @Bind(R.id.LinearLayoutAddProfessionText)
    LinearLayout mLinearLayoutAddProfessionText;
    private List<ProfessionTypeEntity> datas = new ArrayList<>();
    private ProfessionTypeAdapter mProfessionTypeAdapter;
    private List<ProfessionTypeEntity> mParentData;
    private SerializableMap mSelectedMap;
    private String mTitleName;

    @Override
    public int getLayoutId() {
        return R.layout.act_profession;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        mPresenter.getData("zh_version_data.json");
        mSelectedMap = new SerializableMap();// 封装成序列化对象 使用intent传递
        mParentData = new ArrayList<>();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mTitleName = intent.getStringExtra("professionTitleName");
        mSelectedMap = (SerializableMap) bundle.get("map"); // 这个就是我们选中的那个行业和对应的id组成的map
        mTitle.setText(mTitleName);// 进入页面不同标题可能会不同 动态增加标题名字
        mListView.setLayoutManager(new LinearLayoutManager(this));
        if (mSelectedMap != null) {
            mProfessionTypeAdapter = new ProfessionTypeAdapter(this, datas, mParentData, mPresenter, mSelectedMap.getMap());
        } else {
            Map<String, Integer> map = new HashMap<>();
            mSelectedMap = new SerializableMap();
            mProfessionTypeAdapter = new ProfessionTypeAdapter(this, datas, mParentData, mPresenter, map);
        }
        mProfessionTypeAdapter.openLoadAnimation(new ScaleInAnimation());
        mListView.setAdapter(mProfessionTypeAdapter);
//      mListView.addItemDecoration(new DividerDecoration(this));
        StickyRecyclerHeadersDecoration decoration = new StickyRecyclerHeadersDecoration(mProfessionTypeAdapter);
        mListView.addItemDecoration(decoration);
        // 头布局点击事件  点击没有效果 不写会出现小问题
        StickyRecyclerHeadersTouchListener touchListener = new StickyRecyclerHeadersTouchListener(mListView, decoration);
        touchListener.setOnHeaderClickListener(new StickyRecyclerHeadersTouchListener.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(View header, int position, long headerId) {
                Log.i("DNLOG", "headerClick");
            }
        });
        mListView.addOnItemTouchListener(touchListener);
        // checkbox 状态改变监听
        mCheckBoxProfessionList.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCheckBoxProfessionList.setText(getResources().getString(R.string.selected_close));
                    mLinearLayoutAddProfessionText
                            .setVisibility(View.VISIBLE);
                } else {

                    mCheckBoxProfessionList.setText(getResources().getString(R.string.selected_open));
                    mLinearLayoutAddProfessionText.setVisibility(View.GONE);
                }
            }
        });
        /**
         *  搜索功能 edittext变化监听
         */
        mFilterEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        initData();
    }

    /**
     * 搜索 过滤掉不相关的行业
     */
    private void filterData(String filterStr) {
        List<ProfessionTypeEntity> list = new ArrayList<>();
        for (ProfessionTypeEntity model : datas) {
            if (model.getTradeTypeName().toLowerCase().trim().contains(filterStr.toLowerCase().trim())) {
                list.add(model);
            }
        }
        if (list != null ) {
            mProfessionTypeAdapter.updateListView(list);
        }
    }

    /**
     * 需要初始化顶部的选择栏的行业类别
     */
    private void initData() {
        if (mSelectedMap != null && mSelectedMap.getMap() != null) {
            final Map<String, Integer> map = mSelectedMap.getMap();
            mSelectNumber.setText(this.getResources().getString(R.string.limit_profession)+map.size()+"/5");
            mLinearLayoutAddProfessionText.removeAllViews();
            for (Map.Entry entry : map.entrySet()) {
                final String key = (String) entry.getKey();
                final TextView textViewAddressSelected = new TextView(this);
                textViewAddressSelected.setGravity(Gravity.CENTER
                        | Gravity.LEFT);
                textViewAddressSelected.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                textViewAddressSelected.setTextColor(getResources()
                        .getColor(R.color.F1));
                textViewAddressSelected
                        .setBackgroundResource(R.mipmap.adderss_selected_bg);
                textViewAddressSelected.setText(key);
                textViewAddressSelected.setPadding(20, 5, 20, 5);
                mLinearLayoutAddProfessionText.addView(textViewAddressSelected);
                textViewAddressSelected.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLinearLayoutAddProfessionText.removeView(v);
                        map.remove(key);
                        mSelectNumber.setText(ProfessionActivity.this.getResources().getString(R.string.limit_profession)+map.size()+"/5");
                        mProfessionTypeAdapter.notifyData(key);
                    }
                });
            }
        }

    }

    // 接受数据
    @Override
    public void returnProfessionTypeData(List<ProfessionTypeEntity> data) {
        if (data != null) {
            datas.clear();
            for (ProfessionTypeEntity entity : data) {
                if (entity.getParentId() != 0) {
                    datas.add(entity);
                } else {
                    mParentData.add(entity);
                }
            }
            mProfessionTypeAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void returnSelectedData(Map<String, Integer> map) {
        mSelectedMap.setMap(map);
        initData();
    }

    @Override
    public void showLoading(String title) {
    }

    @Override
    public void stopLoading() {
    }

    @Override
    public void showErrorTip(String msg) {
    }

    @OnClick({R.id.backBtn, R.id.title, R.id.Btn_ProfessionType, R.id.textOne})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                finish();
                break;
            case R.id.Btn_ProfessionType:
                break;
            case R.id.textOne: // 确定键
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", mSelectedMap);
                intent.putExtras(bundle);
                this.setResult(100, intent);
                finish();
                break;
        }
    }
}
